package com.zw.utils.encrypt;

import java.math.BigInteger;

// 加密数据计算模块
public class EncryptedDataComputeUtils {
    private RSAAlgorithm rsa = new RSAAlgorithm();
    private PaillierAlgorithm paillier = new PaillierAlgorithm();

    // 执行加密数据计算（加法/乘法同态）
    public BigInteger executeHomomorphicCompute(
            String algorithm,
            String operationType,
            BigInteger ciphertext1,
            BigInteger ciphertext2) {
        if ("RSA".equalsIgnoreCase(algorithm)) {
            if ("multiply".equalsIgnoreCase(operationType)) {
                return rsa.rsaMultiplyHomomorphic(ciphertext1, ciphertext2);
            }
            throw new UnsupportedOperationException("RSA不支持该运算类型");
        } else if ("Paillier".equalsIgnoreCase(algorithm)) {
            if ("add".equalsIgnoreCase(operationType)) {
                return paillier.addHomomorphic(ciphertext1, ciphertext2);
            }
            throw new UnsupportedOperationException("Paillier不支持该运算类型");
        }
        throw new IllegalArgumentException("不支持的算法或运算类型");
    }

    public static void main(String[] args) {
        // 初始化 Paillier 实例（加密解密用同一个实例，确保密钥一致）
        PaillierAlgorithm paillier = new PaillierAlgorithm();

        // 原始明文
        BigInteger rawData1 = BigInteger.valueOf(10);
        BigInteger rawData2 = BigInteger.valueOf(4000);

        // 加密
        BigInteger encryptedData1 = paillier.encrypt(rawData1);
        System.out.println(encryptedData1);
        BigInteger encryptedData2 = paillier.encrypt(rawData2);

        // 加法同态运算（密文操作）
        BigInteger encryptedResult = paillier.addHomomorphic(encryptedData1, encryptedData2);

        // 解密
        BigInteger decryptedResult = paillier.decrypt(new BigInteger("7703411969582273161052545944764625762551199645266116998229162308787997699152946011287211679009469141139816555044697307"));

        System.out.println("原始数据相加：" + (rawData1.add(rawData2)));
        System.out.println("同态计算加法解密结果：" + decryptedResult);


        RSAAlgorithm rsa = new RSAAlgorithm();

        // 原始明文
        BigInteger rsa1 = BigInteger.valueOf(1000);
        BigInteger rsa2 = BigInteger.valueOf(4000);

        // 加密
        BigInteger encryptedRsaData1 = rsa.rsaEncrypt(rawData1);
        BigInteger encryptedRsaData2 = rsa.rsaEncrypt(rawData2);

        // 加法同态运算（密文操作）
        BigInteger rsaEncryptedResult = rsa.rsaMultiplyHomomorphic(encryptedRsaData1, encryptedRsaData2);

        // 解密
        BigInteger rsaDecryptedResult = rsa.rsaDecrypt(rsaEncryptedResult);

        System.out.println("原始数据相乘：" + (rsa1.multiply(rawData2)));
        System.out.println("同态计算乘法解密结果：" + rsaDecryptedResult);
    }
}
